<?php
namespace Home\Controller;

class DingdanController extends CommonController {
	public function pay(){
        $cart = $_SESSION['cart'];
        $cart1['total']=0;
        foreach($cart as $key=>$value){
            $cart1['total']+=$value['total'];
        }
		
		$this->assign('cart1',$cart1);
		$this->display('index');
	}

	public function surepay(){
        $cart = $_SESSION['cart'];
        $cart1['total']=0;
        foreach($cart as $key=>$value){
            $cart1['total']+=$value['total'];
        }
        $data['linkman']=$POST_['linkman'];
		$data['address']=$POST_['address'];
		$data['code']=$POST_['code'];
		$data['phone']=$POST_['phone'];
		$this->assign('cart',$cart);
		$this->assign('cart1',$cart1);
		$this->display('surpay');
		
	}


	public function payaction(){

		$data['linkman'] = $_POST['linkman'];
		$data['address'] = $_POST['address'];
		$data['code'] = $_POST['code'];
		$data['phone'] = $_POST['phone'];
		$data['addtime'] = time();
		$data['u_id'] = $_SESSION['login']['id'];
		$data['status'] = 0;
        $cart = $_SESSION['cart'];
        $cart1['total']=0;
        foreach($cart as $key=>$value){
            $cart1['total']+=$value['total'];
        }
        $data['total']=$cart1['total'];
		//准备sql语句
		$order=D('orders');
		$order->add($data);
		$data=$order->select();
		foreach($data as $val){
			$orderid=$val['id'];
		}
		$orderid=$orderid;
		// //判断插入订单是否成功
		// if($orderid = mysql_insert_id($link)){
			//遍历购物车session里的商品
			foreach($_SESSION['cart'] as $v){
				//循环获得订单中的每个goodid($V['goodsid']相当于goods表中的id)
				//和num($v['num']相当于goods表的store)
				$id = $v['id'];
				$num = $v['num'];
				$goods=D('Goods');

				$goods=$goods->where('id='.$id)->select();
				foreach ($goods as $key => $value) {
					//获取商品表里原有库存
					$store=$value['store'];
				}
				//用商品原有库存减去购物车中商品数量，得到现有库存
				$good['store'] =$store-$num;
				//判断现有商品库存是否大于0，如果是，更新商品库存
				if($good['store']>=0){
					$goods=D('Goods');
					$goods->where('id='.$id)->save($good);
		            
				}else{
					redirect('error');
					
				}
				
				$info['orderid']=$orderid;
				$info['goodsid']=$id;
				$info['num'] = $num;
				$info['name']=$v['goods'];
				$info['price']=$v['price'];
				$detail=D('Detail');
				$detail->add($info);

				$sql = "insert into detail values(null,{$orderid},{$v['id']},'{$v['goods']}',{$v['price']},{$v['num']})";
			}
			 $this->redirect('success');
			// "订单提交成功";
			//unset($_SESSION['cart']);
			
		}
		
		
	}










// }



?>